package com.ruiyou.tb;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;

import androidx.annotation.NonNull;

import com.tencent.smtt.sdk.WebChromeClient;
import com.tencent.smtt.sdk.WebSettings;
import com.tencent.smtt.sdk.WebSettings.LayoutAlgorithm;
import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.sdk.WebViewClient;

import java.lang.ref.WeakReference;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

public class X5WebView extends WebView {
    public static final String AGENT_STR = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.125 Safari/537.36 Edg/84.0.522.59";
    private UDownloadUtil downloadUtil;
    private boolean isX5Core=false;

    public X5WebView(Context arg0) {
        super(arg0);
        //setBackgroundColor(85621);
    }

    public X5WebView(Context arg0, AttributeSet arg1) {
        super(arg0, arg1);
        // WebStorage webStorage = WebStorage.getInstance();
        //检查内核
        isX5Core = getX5WebViewExtension()!= null;
        if (!isX5Core) {
            Toast.makeText(getContext(), "start request X5Core ...", Toast.LENGTH_SHORT).show();
            new APPApplication(new MHandler(this));
        }
        initView();
        initWebViewSettings();
        getView().setClickable(true);
    }
    public void setBundleView(Activity activity, EditText et, ProgressBar pb, View mainView){
        setWebViewClient(new UWebViewClient(et,pb));
        setWebChromeClient(new UWebChromeClient(activity,mainView, pb, isX5Core));
    }
    private void initView() {
        setWebViewClient(new WebViewClient());
        setWebChromeClient(new WebChromeClient());
        downloadUtil = new UDownloadUtil(getContext());
        setDownloadListener(downloadUtil);
        setOnLongClickListener(this);
    }

    @SuppressLint("SetJavaScriptEnabled")
    private void initWebViewSettings() {
        WebSettings webSetting = this.getSettings();
        webSetting.setLayoutAlgorithm(LayoutAlgorithm.NARROW_COLUMNS);
        webSetting.setAppCacheEnabled(true);
        // webSetting.setDatabaseEnabled(true);
        webSetting.setGeolocationEnabled(true);
        webSetting.setAppCacheMaxSize(Long.MAX_VALUE);
        // webSetting.setPageCacheCapacity(IX5WebSettings.DEFAULT_CACHE_CAPACITY);
        //noinspection deprecation
        webSetting.setPluginState(WebSettings.PluginState.ON_DEMAND);
        // webSetting.setRenderPriority(WebSettings.RenderPriority.HIGH);
        webSetting.setCacheMode(WebSettings.LOAD_NO_CACHE);
        //this.getSettingsExtension().setPageCacheCapacity(IX5WebSettings.DEFAULT_CACHE_CAPACITY);//extension
        // settings 的设计
    }

    @Override
    protected boolean drawChild(Canvas canvas, View child, long drawingTime) {
        boolean ret = super.drawChild(canvas, child, drawingTime);
        Paint paint = new Paint();
        paint.setColor(0x7fff0000);
        paint.setTextSize(24.f);
        paint.setAntiAlias(true);
        String core=isX5Core?"X5 Core":"Sys Core";
        canvas.drawText(core, 10, 30, paint);
        return ret;
    }

    public static final int X5_MSG_WHAT_1 = 1056;
    public static final String X5_MSG_KEY_1 = "msg";

    private static class MHandler extends Handler {
        WeakReference<X5WebView> wr;

        public MHandler(X5WebView x5) {
            wr = new WeakReference<>(x5);
        }

        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            X5WebView wv = wr.get();
            if (wv != null && msg.what == X5_MSG_WHAT_1) {
                new AlertDialog.Builder(wv.getContext())
                        .setTitle("Request X5Core result")
                        .setMessage(msg.getData().getString(X5_MSG_KEY_1))
                        .setPositiveButton("OK", null)
                        .create()
                        .show();
            }
        }
    }

    /**
     * 根据名称引用设置方法
     *
     * @param methodName    ...
     * @param needParameter ..
     * @param parameterType .
     * @param parameter     .
     * @return .
     */
    public Object invokeSettingsMethod(String methodName, boolean needParameter, Class<?> parameterType, Object parameter) {
        WebSettings settings = this.getSettings();
        try {
            if (needParameter) {
                Method method = settings.getClass().getMethod(methodName, parameterType);
                return method.invoke(settings, parameter);
            } else {
                Method method = settings.getClass().getMethod(methodName);
                return method.invoke(settings);
            }
        } catch (Exception e) {
            Log.e("InvokeError", methodName);
            e.printStackTrace();
            return null;
        }
    }

    /**
     * Recommend boolean settings
     *
     * @return a editable boolean settings map
     */
    public Map<String, Boolean> getBooleanSettingsMap() {
        Map<String, Boolean> map = new HashMap<>();
        //缩放
        map.put("SupportZoom", true);
        map.put("BuiltInZoomControls", true);
        map.put("DisplayZoomControls", true);
        map.put("UseWideViewPort", true);
        map.put("LoadWithOverviewMode", true);
        //JS
        map.put("JavaScriptEnabled", true);
        map.put("JavaScriptCanOpenWindowsAutomatically", true);
        //access filesystem except res or assets file
        map.put("AllowFileAccess", true);
        //播放优酷网视频等必须为true
        map.put("DomStorageEnabled", true);
        //network
        map.put("LoadsImagesAutomatically", true);
        map.put("BlockNetworkImage", true);
        map.put("BlockNetworkLoads", true);
        //if true must be implemented {UWebChromeClient#onCreateWindow}
        map.put("SupportMultipleWindows", false);
        map.put("DatabaseEnabled", true);
        return map;
    }

    @Override
    public boolean onLongClick(View v) {
        HitTestResult htr = this.getHitTestResult();
        if (htr.getExtra() == null || htr.getType() != HitTestResult.IMAGE_TYPE &&
                htr.getType() != HitTestResult.SRC_IMAGE_ANCHOR_TYPE) {
            return false;
        }
        downloadUtil.downloadPicture(htr.getExtra());
        return true;
    }
}
